import { invoke_proxy } from '@/functions/invoke.ts'
import { BackendResponse } from '@/runtime/response.ts'
import { BACKEND_CODE_OK } from '@/runtime/code.ts'
import { Command as ModelCommand, CommandState, new_command } from '@/models/command.ts'

export class Command {
    protected command: ModelCommand = new_command()
    protected history = false

    constructor(command: ModelCommand, history: boolean) {
        this.command = command
        this.history = history
    }

    /**
     * 获取执行结果
     */
    public get output(): string {
        return this.command.output
    }

    public get statistic(): string {
        return this.command.statistic
    }

    /**
     * 获取命令参数
     */
    public get args(): string {
        return this.command.args
    }

    /**
     * 获取命令ID
     */
    public get id(): string {
        return this.command.command_id
    }

    /**
     * 获取命令名称
     */
    public get name(): string {
        return this.command.name
    }

    /**
     * 获取命令状态
     */
    public get waiting(): boolean {
        return CommandState.WAITING == this.command.state
    }

    /**
     * 获取命令状态
     */
    public get success(): boolean {
        return CommandState.SUCCESS == this.command.state
    }

    /**
     * 获取命令状态
     */
    public get failed(): boolean {
        return CommandState.FAILED == this.command.state
    }

    /**
     * 获取对应的组件
     */
    public get component(): string {
        return this.command.component
    }

    /**
     * 是否是历史命令
     */
    public get is_history(): boolean {
        return this.history
    }

    /**
     * 执行命令的一般实现
     */
    public async execute(): Promise<boolean> {
        if (CommandState.WAITING !== this.command.state) {
            return false
        }

        const response = await invoke_proxy<BackendResponse<ModelCommand>>('invoke_execute_command', { command: this.command })
        if (response.code !== BACKEND_CODE_OK) {
            this.command.state = CommandState.FAILED
            this.command.output = response.message

            return false
        }

        this.command = response.data

        return true
    }

    public toString(): string {
        return this.command.args
    }

    /**
     * 使用方法
     */
    public usage(): string {
        return ''
    }

    /**
     * 命令详细描述
     */
    public description(): string {
        return ''
    }
}
